package com.appspot.checkflames.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import static com.appspot.checkflames.constants.CheckFlamesConstants.*;


public class LoginRequiredFilter implements Filter {

	private static final String AUTHORIZE_URL_PARAM = "authorize_url";
	private static String AUTHORIZE_URL;
	private static String APPLICATION_ID;
	private static String APPLICATION_SECRET;
	
	private static final Logger LOGGER = Logger.getLogger(LoginRequiredFilter.class);
	
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest pRequest, ServletResponse pResponse,
			FilterChain pChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) pRequest;
		String accessToken = (String) request.getSession().getAttribute(ACCESS_TOKEN_PARAM);
		if(accessToken == null || accessToken.length() == 0) {
			HttpServletResponse response = (HttpServletResponse) pResponse;
			LOGGER.info(AUTHORIZE_URL);
			response.sendRedirect(AUTHORIZE_URL);
			return;
		}
		request.setAttribute(APPLICATION_ID_PARAM, APPLICATION_ID);
		request.setAttribute(APPLICATION_SECRET_PARAM, APPLICATION_SECRET);
		pChain.doFilter(pRequest, pResponse);
	}

	public void init(FilterConfig pConfig) throws ServletException {
		AUTHORIZE_URL = pConfig.getInitParameter(AUTHORIZE_URL_PARAM);
		APPLICATION_ID = pConfig.getInitParameter(APPLICATION_ID_PARAM);
		APPLICATION_SECRET = pConfig.getInitParameter(APPLICATION_SECRET_PARAM);
	}

}
